<template>
  <div>
    <div class="list-area">
      <div class="setting-area glo-content-area">
        <div class="title">{{ $t("devicesIndex.devStrEquipment") }}
          <!-- <span>{{ $t("newDevices.configurationMore") }}</span> -->
          <Button type="primary" @click="toAll" style="float:right;margin-right:10px">{{ $t("newDevices.allDevices") }}</Button>
        </div>
        <div class="tip">
          {{ $t("newDevices.addMore") }}
        </div>
        <div class="ul" :class="{open:isOpen==true}">
          <div class="li add" v-if="allPermissions.addEquipments&&tableId!='无'" @click="showAddDevices=true,getData2(),getSiteList(),getParent(),selectionArr=[]">
            <div class="icon">+</div>
            <div class="des">{{ $t("newDevices.addEquipments") }}
            </div>
          </div>
          <div class="li" v-for="(item,index) in list" :key="index">
            <div class="header" >{{item.name}}
              <span style="float:right;margin-right:10px" v-show="item.deviceType=='F800W'">{{item.deviceIntoOrOut==1?$t('devicesCreate.out'):$t('devicesCreate.in')}}</span>
            </div>
            <p>{{$t('devicesCreate.devCreateType')}}: {{item.deviceType}}</p>
            <p>{{$t('devicesIndex.devTableproductType')}}: {{item.productId==1?$t('devicesIndex.devTableMachine'):$t('devicesIndex.devTableGuard')}}</p>
            <p >{{$t('devicesIndex.devTableserial')}}: {{item.sn}}</p>
            <p >
              {{$t('devicesIndex.devTableOnLive')}}: {{item.isOnline==1?$t('devicesIndex.devTableOnlineY'):$t('devicesIndex.devTableOnlineN')}}
              <span v-if="item.isOnline==1" class="zaixian"></span>
              <span v-else  class="buzaixian"></span>
            </p>
            <p>{{$t('versionIndex.verListVersion')}}: {{item.apkInfo}}</p>
            <p>{{$t('devicesIndex.devTableOnPeople')}}: {{item.peopleCount}}</p>
            <div class="caozuo">
              <a @click="showUpdate(item)" v-if="allPermissions.devListEdit">{{ $t("devicesListSettings.devListEdit") }}</a>
              <Divider style="margin:0 4px" type="vertical" v-if="allPermissions.devListEdit&&allPermissions.devListRelieve" />
              <a @click="handleBindArea(item)" v-if="allPermissions.devListRelieve">{{ item.areaId ? $t('devicesListSettings.devListRelieve') : $t('devicesListSettings.devListBind') }}</a>
              <Divider style="margin:0 4px" type="vertical" v-if="allPermissions.devListRelieve||allPermissions.devListCut||allPermissions.devListrestart||allPermissions.devListDel||allPermissions.devTimezones" />
              <Dropdown
                transfer
                v-if="allPermissions.devListCut||allPermissions.devListrestart||allPermissions.devListDel||allPermissions.devTimezones"
              >
                <a>
                  {{ $t("devicesListSettings.devListMore") }}
                  <Icon type="ios-arrow-down" />
                </a>
                <DropdownMenu slot="list">
                  <DropdownItem @click.native="handleOpen(item)" v-if="allPermissions.devListCut">{{ $t("devicesListSettings.devListCut") }}</DropdownItem>
                  <DropdownItem @click.native="handleRestart(item)" v-if="allPermissions.devListrestart">{{ $t("devicesListSettings.devListrestart") }}</DropdownItem>
                  <DropdownItem @click.native="handleDel(item)" v-if="allPermissions.devListDel">{{ $t("devicesListSettings.devListDel") }}</DropdownItem>
                  <DropdownItem @click.native="handleZone(item)" v-if="allPermissions.devTimezones">{{ $t("devicesCreate.devTimezones") }}</DropdownItem>
                  <DropdownItem @click.native="restoreSetting(item)"  v-if="allPermissions.restoreSetting">{{ $t("devicesIndex.restoreSetting") }}</DropdownItem>
                </DropdownMenu>
              </Dropdown>
            </div>
          </div>
          <div v-show="total<=0||!total">{{ $t("newDevices.noEquipment") }}</div>
          <Page
            class="glo-content-area glo-pagenation"
            :total="total"
            :pageSize="pageSize"
            show-sizer
            :current="page"
            show-total
            @on-change="changePage"
            @on-page-size-change="changeSize"
             v-show="total>0"
          />
        </div>
        <!-- <div class="ul"  v-show="total<=0||!total">暂无设备</div> -->
        <div class="bottomTip" v-show="list.length>3">
            <div class="zhankai" v-show="isOpen==false" @click="isOpen=true">
              <Icon type="ios-arrow-down" />
              {{ $t("newDevices.spread") }}
            </div>
            <div class="zhankai" v-show="isOpen" @click="isOpen=false">
              <Icon type="ios-arrow-forward" />
              {{ $t("newDevices.packUp") }}
            </div>
        </div>
        
      </div>
    </div>
    <Create
      v-if="ifCreate"
      @close="closeCreate"
    />
    <Create
      v-if="ifUpdate"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
    <Create2
      v-if="ifD2Update"
      edit-type="update"
      :edit-item="editItem"
      @close="closeUpdate"
    />
    <AreaSelect
      v-if="ifSelectArea"
      :as-cb="areaSelectCallback"
      @close="closeAreaSelect"
    />
    <Modal
        class="modalClass"
        v-model="modalZone"
        width = 600
        :title="$t('devicesCreate.devTimezones')"
        >
        <Form  ref="formItem" :label-width="80">
          <FormItem prop="timezones" :label="$t('devicesCreate.devTimezones')">
            <Select
              style="width:400px"
              v-model="timezone"
              :placeholder="$t('devicesCreate.devTimezonessEL')"
            >
              <Option
                v-for="(item, idx) in timezones" :key="idx"
                :value="item.value"
                :label="item.name"
              >
              </Option>
            </Select>
          </FormItem>
          <FormItem style="margin-top: 120px;">
            <i-button class="submit" type="primary"  @click="handleSubmitZone()">{{ $t("devicesCreate.devCreateSubmit")}}</i-button>
          </FormItem>
        </Form>
        <div slot="footer"></div>
    </Modal>
    <!-- 同步離線記錄 -->
    <Modal
        v-model="modalSel"
         :title="$t('devicesIndex.devOfflineHint')"
        >
          <div style="width:80%;margin:auto; font-size:16px">
            <div style="line-height:40px">{{ $t("devicesIndex.devOfflineAccessIsInfo") }}</div>

            <RadioGroup
              v-model="sex"
              style=" font-size:16px"
            >
              
              <span>{{ $t("devicesIndex.devOfflineAccessIs") }}</span>
              <Radio
               style=" font-size:16px"
                v-for="(item, idx) in sexs" :key="idx"
                :label="item.value"
              >{{ item.name }}</Radio>
            

            </RadioGroup>
          </div>
        <div style="margin-top: 36px; height:40px; overflow: hidden;">
          <i-button style = "float:right; margin-right: 30px;"  type="primary" @click="okSel">{{ $t("devicesIndex.devOfflineAccessSure") }}</i-button>
          <i-button style = "float:right; margin-right: 30px;"  type="text" @click="okCenter">{{ $t("devicesCreate.devCreateCancel") }}</i-button>
        </div>
        <div slot="footer"></div>
    </Modal>
    <!-- 添加设备 -->
    <Modal
        v-model="showAddDevices"
        :title="$t('newDevices.addEquipments')"
        class="modelStyle"
        width = 800
        >
        <div class="adminList" >
          <div style="margin-bottom:20px">
            <!-- <div class="item" style="display:inline-block;margin-right:20px">
              {{$t('newDevices.automaticSearch')}}
            </div> -->
          
            <!-- <Button
              type="primary"
              @click="searchList"
            >
            {{ $t("emailSetting.Search") }}{{ $t("devicesIndex.devStrEquipment") }}
            </Button> -->
            <!-- <div style="float:right;margin-right:20px;margin-top:20px"> -->
            <div style="text-align: right;margin-right:20px;margin-top:20px">
              {{$t('devicesIndex.devSelected')}}{{selectionArr.length}}{{$t('newDevices.entries')}}{{$t('devicesIndex.devStrEquipment')}}
            </div>
          </div>
          <Table
            ref="table"
            class="list"
            :data="list2"
            :columns="columns"
            @on-selection-change="handleSelection"
          />
          <Page
            class="glo-content-area glo-pagenation"
            :total="total2"
            :pageSize="pageSize2"
            show-sizer
            :current="page2"
            show-total
            @on-change="changePage2"
            @on-page-size-change="changeSize2"
          />
          <div class="bind">
            <span style="display:inline-block;margin-right:20px">{{$t('devicesIndex.devBingBtn')}}{{$t('newDevices.site')}}</span>
            <Cascader style="width: 200px;display:inline-block" :data="recordTypes" v-model="recordType" 
              @on-change="handleChange1" :placeholder="$t('newDevices.selectSite')"
              @on-visible-change=" " change-on-select>
            </Cascader>
          </div>
          <i-button style="margin-top: 16px;margin-left: 16px;" class="submit" type="primary"  @click="handleSubmit()">{{ $t("devicesIndex.devBingBtn")}}</i-button>
        </div>
        <div slot="footer"></div>
    </Modal>
    <!-- <Modal
        v-model="areaTypeD"
        title="Common Modal dialog box title"
        @on-ok="ok"
        @on-cancel="cancel">
        <p>Content of dialog</p>
        <p>Content of dialog</p>
        <p>Content of dialog</p>
    </Modal> -->
  </div>
</template>

<script>
import pageMixin from '@/utils/mixins/pageMixin.js'
import Create from './Create'
import Create2 from './Create2'
// import ListSettings from './ListSettings'
import UserListSettings from './UserListSettings'
import AreaSelect from './AreaSelect'
import {
  getList,
  del,
  bindArea,
  upgrade,
  restart,
  reset,
  open,
  IDCard,
  lineAccess,
  openTime,
} from '@/api/device.js'
import {
  getSite,
  getParentArea,
  getDeviceList
} from '@/api/newDevices.js'

// import {getList2}  from '@/api/company.js'
// import UserEdit from './UserEdit'

export default {
  data () {
    return {
      
      list: [],
      page:1,
      pageSize:10,
      total:0,
      sn:'',
      name:'',
      isOpen:false,
      ifD2Update:false,
      ifCreate: false,
      ifUpdate: false,
      editItem: null,
      ifSelectArea: false,
      areaSelectCallback: null,
      modalZone: false,
      itemZoon: '',
      timezone: '',
      timezones: [
        { name: this.$t('devicesCreate.devTimezone1'), value: '(UTC+08:00)' },
        { name: this.$t('devicesCreate.devTimezone5'), value: '(UTC+09:00)' },
        { name: this.$t('devicesCreate.devTimezone7'), value: '(UTC+04:00)' },
        { name: this.$t('devicesCreate.devTimezone8'), value: '(UTC+02:00)' },
        { name: this.$t('devicesCreate.devTimezone9'), value: '(UTC+03:00)' },
        { name: this.$t('devicesCreate.devTimezone12'), value: '(UTC+07:00)' },
        { name: this.$t('devicesCreate.devTimezone14'), value: '(UTC+05:30)' },
        { name: this.$t('devicesCreate.devTimezone18'), value: '(UTC+06:00)' },
        { name: this.$t('devicesCreate.devTimezone20'), value: '(UTC+05:00)' },
        { name: this.$t('devicesCreate.devTimezone22'), value: '(UTC-10:00)' },
        { name: this.$t('devicesCreate.devTimezone23'), value: '(UTC+05:45)' },
        { name: this.$t('devicesCreate.devTimezone25'), value: '(UTC+03:30)' },
        { name: this.$t('devicesCreate.devTimezone27'), value: '(UTC+08:30)' },
        { name: this.$t('devicesCreate.devTimezone28'), value: '(UTC+06:30)' },
        { name: this.$t('devicesCreate.devTimezone29'), value: '(UTC-05:00)' },
        { name: this.$t('devicesCreate.devTimezone33'), value: '(UTC+10:00)' },
        { name: this.$t('devicesCreate.devTimezone34'), value: '(UTC+01:00)' },
        { name: this.$t('devicesCreate.devTimezone38'), value: '(UTC+00:00)' },
        { name: this.$t('devicesCreate.devTimezone41'), value: '(UTC-06:00)' },
        { name: this.$t('devicesCreate.devTimezone47'), value: '(UTC-07:00)' },
        { name: this.$t('devicesCreate.devTimezone48'), value: '(UTC-02:00)' },
        { name: this.$t('devicesCreate.devTimezone50'), value: '(UTC+09:30)' },
        { name: this.$t('devicesCreate.devTimezone51'), value: '(UTC+08:45)' },
        { name: this.$t('devicesCreate.devTimezone52'), value: '(UTC-03:00)' },
      ],
      sex: 0,
      sexs: [
        { name: this.$t('devicesIndex.devOfflineAccessNo'), value: 0 },
        { name: this.$t('devicesIndex.devOfflineAccessYes'), value: 1 },
      ],
      modalSel: false,
      showAddDevices:false,
      list2: [],//添加設備列表
      columns: [
        { type: 'selection', width: 60 },
        {
          type: 'index',
          width: 70,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('devicesIndex.devTableserial'),
          key: 'sn',
        },
        {
          title: this.$t('devicesIndex.devTableName'),
          key: 'name',
        },
        {
          title: this.$t('versionIndex.verListVersion'),
          key: 'apkInfo',
          render (h, { row }) {
            let label = '-'
            if (row.apkInfo) {
              label = row.apkInfo
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('devicesCreate.devCreateType'),
          key: 'deviceType',
        },
        {
          title: this.$t('devicesIndex.devTableproductType'),
          key: 'productId',
          render: (h, { row }) => {
            if (row.productId === 1) {
              return h('div',this.$t('devicesIndex.devTableMachine'))
            } else if (row.productId === 2) {
              return h('div', this.$t('devicesIndex.devTableGuard'))
            }
            return h('div', '-')
          },
        },
        
        // {
        //   title: this.$t('companyManagement.operation'),
        //   key: 'settings',
        //   width: 200,
        //   render: (h, { row }) => {
        //     let from='admin'
        //     return h(UserListSettings, {
        //       props: { row ,from},
        //       on: {
        //         itemClick: (name) => this.handleSettingsClick(name, row),
        //       },
        //     })
        //   },
        // },
      ],
      page2:1,
      pageSize2:10,
      total2:0,
      selectionArr:[],
      recordTypes: [],
      recordType: [],
      allPermissions:{
        devListEdit:false,
        devListRelieve:false,
        devListCut:false,
        devListrestart:false,
        devListDel:false,
        devTimezones:false,
        addEquipments:false,
        restoreSetting:false,
      },
      user:JSON.parse(window.localStorage.getItem('user'))||''
      // areaTypeData:JSON.parse(window.sessionStorage.getItem('editItem'))||'',
      // modal1:false,
    }
  },
  components: {
    UserListSettings,
    Create,
    Create2,
    AreaSelect,
  },
  mounted () {
    this.getData()
    this.getAllPermissions()
  },
  computed: {
    tableId () {
      return this.$store.state.tableId
    },
    btnShow(){
      return this.$store.state.btnShow
    },
    // areaTypeD () {
    //   return this.areaTypeData.areaType=='D'
    // },
  },
  watch: {
    btnShow(){
      this.columns = [
        { type: 'selection', width: 60 },
        {
          type: 'index',
          width: 50,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('devicesIndex.devTableserial'),
          key: 'sn',
        },
        {
          title: this.$t('devicesIndex.devTableName'),
          key: 'name',
        },
        {
          title: this.$t('versionIndex.verListVersion'),
          key: 'apkInfo',
          render (h, { row }) {
            let label = '-'
            if (row.apkInfo) {
              label = row.apkInfo
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('devicesCreate.devCreateType'),
          key: 'deviceType',
        },
        {
          title: this.$t('devicesIndex.devTableproductType'),
          key: 'productId',
          render: (h, { row }) => {
            if (row.productId === 1) {
              return h('div',this.$t('devicesIndex.devTableMachine'))
            } else if (row.productId === 2) {
              return h('div', this.$t('devicesIndex.devTableGuard'))
            }
            return h('div', '-')
          },
        },
      ]
      return this.$store.state.btnShow
    },
    tableId () {
      this.list= [],
      this.page=1,
      this.pageSize=10,
      this.total=0,
      this.getData()
      return this.$store.state.tableId
    },
    
    // areaTypeD () {
    //   // this.modal1=true
    //   return this.areaTypeData.areaType=='D'
    // },
    // modal(){
    //   return this.modal1
    // }
  },
  methods: {
    getAllPermissions(){
      let da=JSON.parse(window.localStorage.getItem('logo'))||[]
      da.map(v => {
        if(v.permission=='#newDevices'&&v.children){
          v.children.map(a=>{
            if(a.permission=='#devList'&&a.children){
              a.children.map(c=>{
                if(c.permission=='#devListEdit3'&&c.checked==='true'){
                  this.allPermissions.devListEdit=true
                } 
                if(c.permission=='#devListRelieve2'&&c.checked==='true'){
                  this.allPermissions.devListRelieve=true
                } 
                if(c.permission=='#devListCut2'&&c.checked==='true'){
                  this.allPermissions.devListCut=true
                } 
                if(c.permission=='#devListrestart2'&&c.checked==='true'){
                  this.allPermissions.devListrestart=true
                } 
                if(c.permission=='#devListDel2'&&c.checked==='true'){
                  this.allPermissions.devListDel=true
                } 
                if(c.permission=='#devTimezones2'&&c.checked==='true'){
                  this.allPermissions.devTimezones=true
                } 
                if(c.permission=='#addEquipments'&&c.checked==='true'){
                  this.allPermissions.addEquipments=true
                } 
                if(c.permission=='#restoreSetting1'&&c.checked==='true'){
                  this.allPermissions.restoreSetting=true
                } 
              })
            }
            
          })
        }
      });
    },
    toAll(){
      this.$router.push({
        path:'device'
      })
    },
    showCreate () {
      this.ifCreate = true
    },
    closeCreate (ifUpdated) {
      ifUpdated && this.getData()
      this.ifCreate = false
    },

    showUpdate (item) {
      console.log('showUpdate')
      console.log(item)
      if(item.deviceType=="D2"){
        this.ifD2Update = true
      }else if(item.deviceType=="F800W"){
        this.ifUpdate = true
      }
      else if(item.deviceType=="D150W"){
        this.$Message.warning(this.$t('devicesIndex.noUpdate'))
      }else{
        this.$Message.warning(this.$t('devicesIndex.noUpdate'))
      }
      
      this.editItem = item
    },
    closeUpdate (ifUpdated) {
      // console.log(ifUpdated)
      // ifUpdated && this.$_page_update()
      this.ifUpdate = false
      this.ifD2Update = false
      this.getData()
    },

    showAreaSelect (cb) {
      this.areaSelectCallback = cb
      console.log(this.areaSelectCallback)
      this.ifSelectArea = true
    },
    closeAreaSelect (ifUpdated) {
      console.log(ifUpdated)
      ifUpdated && this.getData()
      this.ifSelectArea = false
    },

 
    handleSelectionAllStatus (status) {
      this.$refs.table.selectAll(status)
    },
    handleBindAreaMulti () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devStrSel'))
        return
      }
      // 显示区域选择
      console.log('yoyoyooy')
      this.showAreaSelect(async (areaIdSel) => {
      console.log('areaIdSel')

        const arr = nowIds.map(item => {
          return this.handleBind({
            deviceId: item.deviceId,
            areaId: areaIdSel,
            isBind: 1,
          })
        })
        console.log(arr)
        await Promise.all(arr)
      })
    },
    async getData () {
      if(this.tableId=='无'){
        this.list = []
        return
      } 
      const { success, data } = await getList({
        page: this.page,
        limit: this.pageSize,
        sn: this.sn,
        name: this.name,
        areaId:this.tableId,
      })
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = Number(data.count)
      }else{
        // list=this.list1
      }
      this.list = list
      this.page = page
      this.pageSize = this.pageSize
      this.total = total
      this.selection = []
    },
    changeSize(e){
      this.pageSize=e;
      this.getData()
    },
    changePage(e){
      this.page=e
      this.getData()
    },
    changeSize2(e){
      this.pageSize2=e;
      this.getData2()
    },
    changePage2(e){
      this.page2=e
      this.getData2()
    },
    handleSettingsClick (name, row) {
      switch (name) {
        case 'edit':
          console.log('row')
          console.log(row)
          this.showUpdate(row)
          break
        case 'del':
          this.handleDel(row)
          break
        case 'bindArea':
          this.handleBindArea(row)
          break
        case 'restart':
          this.handleRestart(row)
          break
        case 'open':
          this.handleOpen(row)
          break
        case 'Time':
          this.handleTime(row)
          break
        case 'Timezone':
          this.handleZone(row)
          break
        case 'restoreSetting':
          this.restoreSetting(row)
          break
      }
    },
    showUpdate (item) {
      this.editItem = item
       console.log('this.editItem',this.editItem)
      if(item.deviceType=="D2"){
        this.ifD2Update = true
      }else if(item.deviceType=="F800W"){
        this.ifUpdate = true
      }else{
        this.$Message.warning(this.$t('devicesIndex.noUpdate'))
      }
      
      // this.editItem = item
      // console.log('this.editItem',this.editItem)
    },
    async handleDel (item) {
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrDelEquipment'),
        content: this.$t('devicesIndex.devStrDelEquipmentIsNew') + item.name + this.$t('devicesIndex.devStrDelEquipmentIsNNew'),
        onOk: async () => {
          const { success } = await del({ deviceId: item.deviceId })
          if (success) {
            this.$Message.success(this.$t('devicesIndex.devStrDelEquipmentSucc'))
            this.getData()
          } else {
            this.$Message.error(this.$t('devicesIndex.devdevStrDelEquipmentfailed'))
          }
        },
      })
    },
    handleBindArea (item) {
      const { areaId } = item
      if (!areaId) {
        // 显示区域选择
        this.showAreaSelect((areaIdSel) => {
          let arr=[]
          arr.push(
            {
              deviceId: item.deviceId,
              areaId: areaIdSel,
              isBind: 1,
            }
          )
          this.handleBind(arr)
        })
      } else {
        this.$Modal.confirm({
          title: this.$t('devicesIndex.devStrBindRemove'),
          content: this.$t('devicesIndex.devStrdelIsUre') + item.name + this.$t('devicesIndex.devStrdelIsNN'),
          onOk: async () => {
            let arr1=[]
            arr1.push(
              {
                deviceId: item.deviceId,
                areaId,
                isBind: 0,
              }
            )
            this.handleBind(arr1)
          },
        })
      }
    },
    handleupOffline () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devOfflineAccessSel'))
        return
      }
      this.modalSel = true
    },
    okCenter () {
      this.modalSel = false
    },
    okSel () {
      var that = this
      that.selection.forEach((item, index) => {
        that.handleLineAccess({
          sn: item.sn,
          needPhoto: that.sex,
        })
      })
    },
    handleUpgradeaMulti () {
      const nowIds = this.selection
      if (nowIds.length === 0) {
        this.$Message.warning(this.$t('devicesIndex.devStrSelupgrade'))
        return
      }
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrupgradeEquipment'),
        content: this.$t('devicesIndex.devStrupgradeEquipmentIs'),
        onOk: async () => {
          const arr = nowIds.map(item => {
            return this.handleUpgrade({
              sn: item.sn,
            })
          })
          await Promise.all(arr)
        },
      })
    },
    handleRestart (item) {
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrRestart'),
        content: this.$t('devicesIndex.devStrRestartIsNew') + item.name + this.$t('devicesIndex.devStrDelEquipmentIsNNew'),
        onOk: async () => {
          // const { success, data } = await restart({ sn: item.sn})
          const { success, data } = await restart({ sn: item.sn ,protocolVersion:item.protocolVersion})
          if (success) {
            this.$Message.success(this.$t('devicesIndex.devStrRestarsUCC'))
            this.getData()
          } else {
            this.$Message.error(data)
          }
        },
      })
    },
    handleOpen (item) {
      console.log('open')
      this.$Modal.confirm({
        title: this.$t('devicesIndex.devStrEquipmentName'),
        content: this.$t('devicesIndex.devStrEquipment') + item.name + this.$t('devicesIndex.devStrCutIs'),
        onOk: async () => {
          const { success, data } = await open({ sn: item.sn})
          if (success) {
            this.$Message.success(this.$t('devicesIndex.devStrCutSucc'))
            this.getData()
          } else {
            this.$Message.error(data)
          }
        },
      })
    },
    handleTime (item) {
      this.$Modal.confirm({
        title: this.$t('devicesListSettings.devListTimeIs'),
        content: this.$t('devicesIndex.devStrEquipment') + item.name + this.$t('devicesListSettings.devListTimeIs'),
        onOk: async () => {
          const { success, data } = await openTime({ sn: item.sn })
          if (success) {
            this.$Message.success(this.$t('devicesListSettings.devListTimeSucc'))
            this.getData()
          } else {
            this.$Message.error(this.$t('devicesListSettings.devListTimeErr'))
          }
        },
      })
    },
    handleZone (item) {
      this.timezone = item.timezone
      this.modalZone = true
      this.itemZoon = item
    },
    restoreSetting(item){
      this.$Modal.confirm({
        title: this.$t('devicesIndex.restoreSetting'),
        content: this.$t('devicesIndex.devOfflineAccessSure') + item.name + this.$t('devicesIndex.restoreSetting'),
        onOk: async () => {
          // const { success, data } = await reset({ sn: item.sn})
          const { success, data } = await reset({ sn: item.sn ,protocolVersion: item.protocolVersion})
          if (success) {
            this.$Message.success(this.$t('devicesIndex.restoreSetting')+this.$t('staffIndex.staffDepaUser2'))
            this.getData()
          } else {
            this.$Message.error(data)
          }
        },
      })
    },
    async handleSubmitZone () {
      if (!this.timezone) {
        this.$Message.error(this.$t('devicesIndex.devtimezoneSel'))
        return
      }
      if (this.timezone == this.itemZoon.timezone) {
        this.$Message.error(this.$t('devicesIndex.devtimezoneNew'))
        return
      }
      const { success } = await openTime({
        sn: this.itemZoon.sn,
        timezone: this.timezone,
        deviceId: this.itemZoon.deviceId,
        protocolVersion: this.itemZoon.protocolVersion,
      })
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devtimezoneNewSucc'))
        this.modalZone = false
        this.getData()
      } else {
        this.$Message.error(this.$t('devicesIndex.devtimezoneNewErr'))
      }
    },
    async handleBind (params) {
      console.log('handleBind')
      const { success } = await bindArea(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devdevStrUpdateSucc'))
        this.getData()
      } else {
        this.$Message.error(this.$t('devicesIndex.devdevStrUpdatefailed'))
      }
    },
    async handleUpgrade (params) {
      const { success, data } = await upgrade(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devdevStrupgradeSucc'))
        this.getData()
      } else {
        this.$Message.error(this.$t('devicesIndex.devdevStrupgradeErr'))
      }
    },
    async handleLineAccess (params) {
      const { success, data } = await lineAccess(params)
      if (success) {
        this.$Message.success(this.$t('devicesIndex.devOfflineAccessSucc'))
        this.modalSel = false
        this.getData()
      } else {
        this.$Message.error(this.$t('devicesIndex.devOfflineAccessErr'))
      }
    },
    async getData2 () {
      const { success, data } = await getDeviceList(
        {
        page: this.page2,
        limit: this.pageSize2,
        // areaId:this.tableId,
        // isBindArea:0
        }
      )
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = Number(data.count)
      }
      this.list2 = list
      this.page2 = page
      this.total2 = total
    },
    //添加设备绑定场所
    async handleSubmit(){
      if(this.selectionArr.length<=0){
        this.$Message.error(this.$t('devicesIndex.devOfflineAccessSel'))
        return
      }
      let deviceIdArr=[]
      this.selectionArr.forEach(v=>{
        let data2={
          deviceId:v.deviceId,
          areaId: this.recordType[this.recordType.length-1],
          isBind:1,
          protocolVersion:v.protocolVersion,
          deviceType:v.deviceType
        }
        deviceIdArr.push(data2)
      })
      
      // const { success, data } = await bindArea(deviceIdArr)
      const res = await bindArea(deviceIdArr)
      // let data=res.data
      // console.log('data',res)
      if(res.data.code==0){
        this.$Message.success(this.$t('staffIndex.staffeAddS'))
        this.showAddDevices = false
        this.getData()
      }
      else if(res.data=="此版本暂不支持该设备型号"){
        this.$Message.error(this.$t('devicesIndex.devAddEquipment'))
      }
      else if(res.data=="设备绑定数量不能超过"){
        // console.log('data.num',res.body.num)
        this.$Message.error(this.$t('devicesIndex.devAddEquipmentTip')+res.body.num)
      }
      else{
        this.$Message.error(this.$t('staffIndex.staffeAddE'))
      }
      
      // if (data) {
      //   console.log('databind',data)
      //   if(data.code==0){
      //     this.$Message.success(this.$t('staffIndex.staffeAddS'))
      //     this.showAddDevices = false
      //     this.getData()
      //   }
      // } else {
      //   console.log('databind22',data,data.code)
      //   if(data=="此版本暂不支持该设备型号"){
      //     this.$Message.error(this.$t('devicesIndex.devAddEquipment'))
      //   }
      //   else if(data=="此版本暂不支持该设备型号"){
      //     this.$Message.error(this.$t('devicesIndex.devAddEquipment'))
      //   }else{
      //     this.$Message.error(this.$t('staffIndex.staffeAddE'))
      //   }
      // }
    },
    searchList(){

    },
    handleSelection (selection = []) {
      console.log(selection)
      // console.log(11111)
      this.selectionArr = selection
    },
    handleChange1 (value) {
      // Change时候赋值给recordType  然后关闭级联下拉框可以选中
      this.recordType = value
      // if(value){       
      //   this.areaId = value[value.length-1]
      // }
    },
    async getSiteList(){
       const { success ,data} = await getSite()
      if (success) {
        const list=data.data
        let listString = JSON.stringify(list).replace(/"id"/g, '"value"')
        let listStringLabel = listString.replace(/"areaName"/g, '"label"')
        let listStringChildren = listStringLabel.replace(/"children"/g, '"children"')
        var aParse = JSON.parse(listStringChildren)
        var firstItem=aParse[0].value
        var that=this
        function dG(params) {
        params.forEach(v=>{
          if(v.value!=firstItem){
            if(that.user.type!='0'){
              if(v.areaType=='D'&&v.value!=that.user.areaId){
                v.disabled=true
              }
            }
          }
          if(v.children){
            dG(v.children)
          }else{
            v.children=[]
            
          }
        })
      }
      dG(aParse)
      if(aParse&&aParse[0].label==="新场所"){
          let arr11=aParse
          arr11[0].label=this.$t('title.newSite')
          this.recordTypes=arr11
        }else{
          this.recordTypes=aParse 
        }
        // if(aParse[0].disabled){
        //   this.recordTypes=aParse[0].children
        // }else{
        //   this.recordTypes=aParse
        // }
        
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    // 获取上级场所
    async getParent(){
      console.log('getParentAreas123')
      let editItem1=window.sessionStorage.getItem('editItem')||''
      let editItem=JSON.parse(editItem1)
      console.log('editItem',editItem)
      let data1={
        id:editItem.id,
        parentId: editItem.parentId,
      }
      console.log('data1',data1)
      const { success ,data} = await getParentArea(data1)
      if (success) {
        setTimeout(() => {
          this.recordType=data.data
        }, 500);
        
      } else {
        this.$Message.error(this.$t('staffIndex.stafferror'))
      }
    },
    
  },
}
</script>

<style lang="less" scoped>
@color: #2d8cf0;
.list-area{
  overflow: hidden;
  width: auto;
  min-height: 300px;
  margin-bottom: 30px;
  background-color: #fff;
  position: relative;
  .setting-area{
    padding-bottom: 30px;
    .title{
      line-height: 32px;
      font-size: 18px;
      font-weight: bold;
      
      span{
        font-size: 14px;
        font-weight: normal;
        margin-left: 10px;
        color:@color
      }
    }
    .tip{
      margin-bottom: 20px;
    }
    .ul{
      width: auto;
      height:280px;
      // position: relative;
      overflow: hidden;
      .clearfix();
      // padding-bottom: 30px;
      &.open{
        height: auto;
      }
      .li{
        padding: 0;
        margin: 0;
        overflow: hidden;
        // padding-top: 10px;
        // box-sizing: border-box;
        width: 23%;
        // height: 250px;
        min-height: 280px;
        line-height: 26px;
        background-color: #f5f5f5;
        margin-bottom: 10px;
        margin-right: 2%;
        // float: left;
        display: inline-block;
        .header{
          height: 40px;
          line-height: 40px;
          font-weight: bold;
          border-bottom: 1px solid #ccc;
          padding: 0 20px;
          margin: 0;
          margin-bottom: 10px;
        }
        p{
          margin: 0;
          padding: 0 20px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
          // position: relative;
          .zaixian{
            // content: '';
            // display: block;
            width: 16px;
            height: 16px;
            display: inline-block;
            margin-left: 10px;
            vertical-align: middle;
            background-color: green;
            // position: absolute;
            // left: 50%;
            // top:50%;
            border-radius: 50%;
            // transform: translate(-50%,-50%);
          }
          .buzaixian{
            border-radius: 50%;
            width: 16px;
            height: 16px;
            display: inline-block;
            margin-left: 10px;
            vertical-align: middle;
            background-color: gray;
          }
        }
        .caozuo{
          margin: 0;
          padding: 0 10px 0 20px;
        }
        
      }
      .li.add{
        // min-height: 250px;
        cursor: pointer;
        &:hover{
          border: 1px solid #2d8cf0;
        }
        .icon{
          width: 160px;
          height: 160px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 80px;
          margin: 0 auto;
        }
        .des{
          // margin: 0 auto;
          // display: block;
          text-align: center;
          font-size: 16px;
        }
      }
    }
    .bottomTip{
        position: absolute;
        bottom: 6px;
        right: 10px;
        font-size: 16px;
        color: @color;
    }
  }
  
}
.adminList{
  position: relative;
  .bind{
    position: absolute;
    bottom: 66px;
    left:20px;
  }
}
</style>
